<template>
  <div class="bom-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">物料清单（BOM）管理</span>
          <div class="header-actions">
            <ImportButton 
              data-type="bom" 
              @import-success="handleImportSuccess"
            />
            <ExportButton
              :data="tableData"
              :columns="exportColumns"
              filename="物料清单"
            />
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              新增BOM
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" class="search-form">
        <el-form-item label="产品名称">
          <el-input v-model="searchForm.productName" placeholder="请输入产品名称" clearable />
        </el-form-item>
        <el-form-item label="产品编码">
          <el-input v-model="searchForm.productCode" placeholder="请输入产品编码" clearable />
        </el-form-item>
        <el-form-item label="BOM版本">
          <el-input v-model="searchForm.version" placeholder="请输入版本号" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table :data="tableData" border stripe>
        <el-table-column type="expand">
          <template #default="{ row }">
            <div class="expand-content">
              <h4>物料明细</h4>
              <el-table :data="row.items" border size="small">
                <el-table-column prop="seq" label="序号" width="80" />
                <el-table-column prop="materialCode" label="物料编码" width="150" />
                <el-table-column prop="materialName" label="物料名称" width="200" />
                <el-table-column prop="spec" label="规格" width="150" />
                <el-table-column prop="quantity" label="用量" width="100" />
                <el-table-column prop="unit" label="单位" width="80" />
                <el-table-column prop="lossRate" label="损耗率(%)" width="100" />
                <el-table-column prop="remark" label="备注" />
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="编号" width="80" />
        <el-table-column prop="productCode" label="产品编码" width="150" />
        <el-table-column prop="productName" label="产品名称" width="200" />
        <el-table-column prop="version" label="BOM版本" width="120" />
        <el-table-column prop="itemCount" label="物料数量" width="100">
          <template #default="{ row }">
            <el-tag>{{ row.items.length }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="totalCost" label="总成本" width="120">
          <template #default="{ row }">
            <span style="color: #f56c6c; font-weight: bold;">
              ¥{{ row.totalCost.toFixed(2) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? '当前版本' : '历史版本' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="success" @click="handleCopy(row)">复制</el-button>
            <el-button link type="info" @click="handleViewCost(row)">成本分析</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSearch"
        @current-change="handleSearch"
      />
    </el-card>

    <!-- BOM编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle"
      width="1200px"
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="产品编码" prop="productCode">
              <el-input v-model="form.productCode" placeholder="请输入产品编码" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入产品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="BOM版本" prop="version">
              <el-input v-model="form.version" placeholder="例如: V1.0" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">物料明细</el-divider>

        <div class="bom-items">
          <div class="item-header">
            <span>物料清单</span>
            <el-button type="primary" size="small" @click="handleAddItem">
              <el-icon><Plus /></el-icon>
              添加物料
            </el-button>
          </div>

          <el-table :data="form.items" border>
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column label="物料编码" width="150">
              <template #default="{ row }">
                <el-input v-model="row.materialCode" placeholder="物料编码" />
              </template>
            </el-table-column>
            <el-table-column label="物料名称" width="180">
              <template #default="{ row }">
                <el-input v-model="row.materialName" placeholder="物料名称" />
              </template>
            </el-table-column>
            <el-table-column label="规格" width="150">
              <template #default="{ row }">
                <el-input v-model="row.spec" placeholder="规格" />
              </template>
            </el-table-column>
            <el-table-column label="用量" width="100">
              <template #default="{ row }">
                <el-input-number v-model="row.quantity" :min="0" :precision="2" />
              </template>
            </el-table-column>
            <el-table-column label="单位" width="100">
              <template #default="{ row }">
                <el-input v-model="row.unit" placeholder="单位" />
              </template>
            </el-table-column>
            <el-table-column label="损耗率(%)" width="100">
              <template #default="{ row }">
                <el-input-number v-model="row.lossRate" :min="0" :max="100" :precision="1" />
              </template>
            </el-table-column>
            <el-table-column label="单价" width="100">
              <template #default="{ row }">
                <el-input-number v-model="row.unitPrice" :min="0" :precision="2" />
              </template>
            </el-table-column>
            <el-table-column label="小计" width="100">
              <template #default="{ row }">
                {{ calculateItemCost(row).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="备注">
              <template #default="{ row }">
                <el-input v-model="row.remark" placeholder="备注" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80" fixed="right">
              <template #default="{ $index }">
                <el-button link type="danger" @click="handleDeleteItem($index)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="cost-summary">
            <el-descriptions :column="4" border>
              <el-descriptions-item label="物料总成本">
                <span class="cost-value">¥{{ calculateTotalCost().toFixed(2) }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="损耗成本">
                <span class="cost-value">¥{{ calculateLossCost().toFixed(2) }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="含损耗总成本">
                <span class="cost-value total">¥{{ calculateTotalWithLoss().toFixed(2) }}</span>
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </div>

        <el-form-item label="备注">
          <el-input 
            v-model="form.remark" 
            type="textarea" 
            :rows="2"
            placeholder="请输入备注信息" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </template>
    </el-dialog>

    <!-- 成本分析对话框 -->
    <el-dialog v-model="costDialogVisible" title="BOM成本分析" width="900px">
      <div class="cost-analysis">
        <el-row :gutter="20">
          <el-col :span="12">
            <div id="costPieChart" style="height: 400px;"></div>
          </el-col>
          <el-col :span="12">
            <div id="costBarChart" style="height: 400px;"></div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import ImportButton from '@/components/common/ImportButton.vue'
import ExportButton from '@/components/common/ExportButton.vue'

// 搜索表单
const searchForm = reactive({
  productName: '',
  productCode: '',
  version: ''
})

// 导出列配置
const exportColumns = [
  { prop: 'productCode', label: '产品编码' },
  { prop: 'productName', label: '产品名称' },
  { prop: 'version', label: 'BOM版本' },
  { prop: 'totalCost', label: '总成本' }
]

// 表格数据
const tableData = ref([
  {
    id: 1,
    productCode: 'P001',
    productName: 'iPhone 15',
    version: 'V1.0',
    totalCost: 4650,
    status: 1,
    createTime: '2024-01-15 10:30:00',
    items: [
      { seq: 1, materialCode: 'MAT002', materialName: 'OLED屏幕', spec: '6.1英寸', quantity: 1, unit: '片', lossRate: 2, unitPrice: 800, remark: '' },
      { seq: 2, materialCode: 'MAT003', materialName: 'A17芯片', spec: '3nm工艺', quantity: 1, unit: '颗', lossRate: 1, unitPrice: 1200, remark: '' },
      { seq: 3, materialCode: 'MAT004', materialName: '电池组件', spec: '3349mAh', quantity: 1, unit: '个', lossRate: 3, unitPrice: 150, remark: '' },
      { seq: 4, materialCode: 'MAT005', materialName: '包装盒', spec: '标准包装', quantity: 1, unit: '个', lossRate: 5, unitPrice: 15, remark: '' }
    ]
  },
  {
    id: 2,
    productCode: 'P001',
    productName: 'iPhone 15',
    version: 'V0.9',
    totalCost: 4580,
    status: 0,
    createTime: '2024-01-10 14:20:00',
    items: [
      { seq: 1, materialCode: 'MAT002', materialName: 'OLED屏幕', spec: '6.1英寸', quantity: 1, unit: '片', lossRate: 2, unitPrice: 800, remark: '' },
      { seq: 2, materialCode: 'MAT003', materialName: 'A17芯片', spec: '3nm工艺', quantity: 1, unit: '颗', lossRate: 1, unitPrice: 1180, remark: '旧版本' }
    ]
  }
])

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 2
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('新增BOM')
const formRef = ref(null)
const costDialogVisible = ref(false)

// 表单数据
const form = reactive({
  id: null,
  productCode: '',
  productName: '',
  version: '',
  remark: '',
  items: []
})

// 表单验证规则
const rules = {
  productCode: [{ required: true, message: '请输入产品编码', trigger: 'blur' }],
  productName: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
  version: [{ required: true, message: '请输入BOM版本', trigger: 'blur' }]
}

// 计算物料项成本
const calculateItemCost = (item) => {
  return item.quantity * item.unitPrice * (1 + item.lossRate / 100)
}

// 计算总成本（不含损耗）
const calculateTotalCost = () => {
  return form.items.reduce((sum, item) => sum + item.quantity * item.unitPrice, 0)
}

// 计算损耗成本
const calculateLossCost = () => {
  return form.items.reduce((sum, item) => {
    return sum + item.quantity * item.unitPrice * (item.lossRate / 100)
  }, 0)
}

// 计算含损耗总成本
const calculateTotalWithLoss = () => {
  return calculateTotalCost() + calculateLossCost()
}

// 搜索
const handleSearch = () => {
  console.log('搜索:', searchForm)
  ElMessage.success('查询成功')
}

// 重置
const handleReset = () => {
  searchForm.productName = ''
  searchForm.productCode = ''
  searchForm.version = ''
  handleSearch()
}

// 导入成功回调
const handleImportSuccess = (result) => {
  ElMessage.success(`成功导入 ${result.validRows} 条数据`)
  handleSearch()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增BOM'
  Object.assign(form, {
    id: null,
    productCode: '',
    productName: '',
    version: '',
    remark: '',
    items: []
  })
  dialogVisible.value = true
}

// 添加物料项
const handleAddItem = () => {
  form.items.push({
    materialCode: '',
    materialName: '',
    spec: '',
    quantity: 1,
    unit: '',
    lossRate: 0,
    unitPrice: 0,
    remark: ''
  })
}

// 删除物料项
const handleDeleteItem = (index) => {
  form.items.splice(index, 1)
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑BOM'
  Object.assign(form, {
    ...row,
    items: JSON.parse(JSON.stringify(row.items))
  })
  dialogVisible.value = true
}

// 复制
const handleCopy = (row) => {
  dialogTitle.value = '复制BOM'
  Object.assign(form, {
    id: null,
    ...row,
    version: row.version + '_copy',
    items: JSON.parse(JSON.stringify(row.items))
  })
  dialogVisible.value = true
}

// 提交
const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (form.items.length === 0) {
        ElMessage.warning('请至少添加一条物料明细')
        return
      }
      console.log('提交:', form)
      ElMessage.success(form.id ? '修改成功' : '新增成功')
      dialogVisible.value = false
      handleSearch()
    }
  })
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除BOM "${row.productName} ${row.version}" 吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
  })
}

// 查看成本分析
const handleViewCost = (row) => {
  costDialogVisible.value = true
  ElMessage.info('成本分析图表功能需要集成ECharts库')
}
</script>

<style scoped>
.bom-page {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-form {
  margin-bottom: 20px;
}

.expand-content {
  padding: 20px;
  background: #fafafa;
}

.expand-content h4 {
  margin: 0 0 15px 0;
  color: #303133;
}

.bom-items {
  margin-bottom: 20px;
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  font-weight: bold;
}

.cost-summary {
  margin-top: 20px;
}

.cost-value {
  color: #f56c6c;
  font-weight: bold;
  font-size: 16px;
}

.cost-value.total {
  font-size: 18px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

.cost-analysis {
  padding: 20px;
}
</style>

